/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2022年2月1日
 */
package com.massyframework.beanskin.util.config;

import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;

import com.massyframework.beanskin.Module;
import com.massyframework.beanskin.util.localstore.LocalStore;

/**
 * 配置加载工具
 * @author huangkh
 *
 */
public abstract class ConfigurationLoaderUtils {
	
	private static final String CLASS_PATH = "BEANSKIN-INF/config/";
	private static final String EXTENDS    = "extends";

	/**
	 * 定位配置文件路经
	 * @param module {@link Module},模块
	 * @param localStore {@link LocalStore}, 本地存储
	 * @param fileName {@link String}, 不包括前置的目录的文件名
	 * @return {@link URL}, 配置文件的URL地址
	 */
	public static URL locateConfigurationUrl(Module<?> module, 
			LocalStore localStore,  String fileName){
		// 1.先在扩展路经查找配置文件
		URL result = locateByExtendsDir(module, localStore, fileName);
		if (result == null) {
			// 2.如果照不到扩展的配置，则使用缺省的配置文件
			result = module.getModuleClassLoader().getResource(CLASS_PATH.concat(fileName));
		}
		return result;
	}
	
	/**
	 * 在扩展目录下定位配置文件
	 * @param module {@link Module},模块
	 * @param localStore {@link LocalStore}, 本地存储
	 * @param fileName  {@link String}, 不包括前置的目录的文件名
	 * @return {@link URL}, 配置文件的URL地址
	 */
	protected static URL locateByExtendsDir(Module<?> module, 
			LocalStore localStore, String fileName)  {
		Path path = localStore.getConfigDirectory(module).resolve(EXTENDS).resolve(fileName);
		if (Files.exists(path)) {
			try {
				return path.toUri().toURL();
			} catch (MalformedURLException e) {
			}
		}
		return null;
	}

}
